/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package camara;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ivan
 */
public class KMtronic extends Thread{
    
    
    private Reles tv;
    public int rele;
    public int estadoRele;
    public String sIP;
    
    
    public KMtronic(Object tv, String add){
        rele=0;
        estadoRele=0;
        sIP=add;
        this.tv = (Reles) tv;
        
    }
    public void pulsadorRele(int rele){
        this.rele=rele;
        this.estadoRele=2;
        
    }
    public void setRele(int rele){
        this.rele=rele;
        this.estadoRele=1;
    }
    public void resetRele(int rele){
        this.rele=rele;
        this.estadoRele=0;
    }
    private int gestionaRele() throws IOException{
        try {
            byte[] cadena = new byte[8];
            
            int leidos;
            String orden = "http://" + this.sIP + "/index.html?R";
            orden = orden + this.rele + "=" + this.estadoRele;
            URL url = new URL(orden);
            InputStream in = url.openStream();
            leidos=in.read(cadena,0,7);
            
            in.close();
            String enTexto = new String(cadena);
            enTexto.trim();
            
            String mierda = enTexto.substring(0,3);
            
            if (mierda.equals("ACK"))
                return 0;
            else 
                return -1;
                
                
            
            
            

                
            

            
        } catch (MalformedURLException ex) {
            Logger.getLogger(KMtronic.class.getName()).log(Level.SEVERE, null, ex);
           
        }
        return 0;
    }
    @Override
    public void run(){
        URL url;
        while (true){
            try {
                Thread.sleep(100); // 100mS
            
            } catch (InterruptedException ex) {
                Logger.getLogger(KMtronic.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (this.rele!=0){   // Si el rele es distinto de cero hay movimiento
                try {
                    
                    if (gestionaRele()==0)
                        this.tv.PonEstadoReles(this.rele,this.estadoRele);
                    this.rele = 0;
                } catch (IOException ex) {
                    Logger.getLogger(KMtronic.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
        }
        
        
    }
        

}
